<template>
  <div class="app-container">
    <el-form :model="form" ref="form" size="small" inline label-width="68px">
        <el-form-item label="公司" prop="companyId" display="inline" required>
          <el-select v-model="form.companyId" placeholder="请选择公司" v-on:change="getShopList"  >
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="门店" prop="shopId" display="inline" required>
          <el-select v-model="form.shopId" v-on:change="getGoodsList" placeholder="请选择门店">
            <el-option
              v-for="item in shopList"
              :key="item.id"
              :label="item.shopName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="供应商" prop="supplyId" required>
          <el-select v-model="form.supplyId" placeholder="请选择供货商">
            <el-option
              v-for="item in supplyList"
              :key="item.supplyId"
              :label="item.sname"
              :value="item.supplyId +'|'+item.sname"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="送货时间" label-width="120px" prop="acceptTime"  required>
          <el-date-picker
            :picker-options="{ disabledDate: disabledDate }"
            v-model="form.acceptTime"
            placeholder="请输入供货商送货时间"
            type="datetime"
            default-time="10:00:00"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

    </el-form>

    <el-button type="primary" icon="el-icon-plus" size="mini" @click="selGoods">清单商品</el-button>
    <el-table :data="goodsSelect" style="margin-top: 20px">
      <!-- 隐藏id列 -->
      <el-table-column prop="goodsid" width="100" ><template slot-scope="scope"><el-input type="hidden" v-model="scope.row.goodsid" /></template></el-table-column>
      <el-table-column prop="goodsName" label="商品名称" ></el-table-column>
      <el-table-column prop="goodsNum" isedit label="商品数量" ><div slot-scope="scope"><el-input v-model="scope.row.goodsNum" /></div> </el-table-column>
      <el-table-column prop="goodsUnit"  label="单位" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_goods_unit" :value="scope.row.goodsUnit"/>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="商品价格" ><div slot-scope="scope"><el-input v-model="scope.row.price" /></div> </el-table-column>
      <el-table-column prop="totalPrice" label="小计"  ><div slot-scope="scope"><el-input readonly  v-model="(scope.row.price * scope.row.goodsNum).toFixed(2)" /></div></el-table-column>
      <el-table-column prop="stock" label="当前库存" />
      <el-table-column prop="remarkShop" label="备注" ><div slot-scope="scope"><el-input v-model="scope.row.remarkShop" /></div> </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" @click="handleDelete(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px;text-align: right;">合计：<span style="color: red">{{totalPrice}}</span>元</div>

    <el-form :model="form" ref="form" size="small" label-width="68px" style="bottom: 0;position: fixed;width: 100%;background-color: #fff;padding: 10px;">
      <el-form-item  label="备注" prop="remark"  style="width: 80%" >
        <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :autosize="{minRows: 3, maxRows: 3}" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="submitForm">提交</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <!-- 添加采购商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="采购商品"  prop="goods_name">
          <el-select v-model="goods" multiple filterable placeholder="请选择商品" >
            <el-option
              v-for="item in goodsList"
              :key="item.id"
              :label="item.name"
              :value="item.id+'|'+item.stock+'|'+item.price+'|' + item.name+'|'+item.unit"
            >
            </el-option>
          </el-select>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleGoods">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrderlist, getOrderlist, delOrderlist, addOrderlist, updateOrderlist,formatDate } from "@/api/system/orderlist"
import { listSupply} from "@/api/system/supply"
import { listCompany,listShop} from "@/api/system/shop"
import {listCompanyGoods, listCompanyGoods_stock} from "@/api/system/companyGoods"

export default {
  name: "Orderlist",
  dicts: ['sys_goods_unit'],
  computed: {
    totalPrice() {
      let total = 0
      for (let i = 0; i < this.goodsSelect.length; i++) {
        const item = this.goodsSelect[i]
        total += item.price * item.goodsNum
      }
      return total
    }
  },
  data() {
    return {
      //我的供货商列表
      supplyList: [],
      //公司列表
      companyList: [],
      //门店列表
      shopList: [],
      //商品列表
      goodsList: [],
      //选中商品
      goods:"",
      //已选择商品列表
      goodsSelect:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购单表格数据
      orderlistList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 品类数量时间范围
      daterangeCtime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ctime: null,
        acceptTime: null,
        arriveTime: null,
        status: null,
        orderNo: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getSupplyList()
    this.getCompanyList()
  },
  methods: {
    //限制时间
    disabledDate(time){
      return time.getTime() < (Date.now() -1000*60*60*24)
    },
    selGoods(){
      //判断是否已经选择了店铺
      if(this.form.shopId == null || this.form.shopId == ""){
        this.$message.error("请先选择门店")
        return false
      }
      //查询商品列表，附带库存信息
      // this.getGoodsList()

      this.open = true
    },
    //删除该商品
    handleDelete(index){
      this.goodsSelect.splice(index, 1)
    },
    //处理选中的商品
    handleGoods(){
      console.log("选中商品：",this.goods)
      this.goodsSelect = []
      for (let i = 0; i < this.goods.length; i++) {
        const item = this.goods[i]
        const detail = item.split("|")
        this.goodsSelect.push({"goodsid":detail[0],"goodsName":detail[3],"goodsNum":1,"stock":detail[1],"price":detail[2],"totalPrice":detail[2],"goodsUnit":detail[4]})
      }
      this.open = false
    },

    //获取商品列表
    getGoodsList(){
      var shopId = this.form.shopId
      console.log("gl shopId is :",shopId)
      if(shopId == null || shopId == "") return false
      listCompanyGoods_stock({"shopId": shopId,"noPage":"1"}).then(response => {
        console.log("response:",response)
        this.goodsList = response.rows
        this.goodsSelect=[]
        this.goods = ""
      })
    },

    //获取公司列表
    getCompanyList(){
      listCompany({}).then(response => {
        this.companyList = response.rows
      })
    },

    //获取门店列表
    getShopList(){
      //清空门店列表
      this.shopList = []
      //获取当前选中的公司ID
      const companyId = this.form.companyId
      listShop({"companyId":companyId}).then(response => {
        this.shopList = response.rows
      })
    },

    //获取供应商列表
    getSupplyList(){
      listSupply({"status":"1"}).then(response => {
        this.supplyList = response.rows
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
      }
      this.goodsSelect = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCtime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 提交按钮 */
    submitForm() {



      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.form.id) {
            updateOrderlist(this.form).then(response => {
              this.loading = false
              this.$message.success("修改成功")
              this.reset()
              })
          } else {
            //格式化acceptTime
            var acceptTime = this.form.acceptTime
            this.form.acceptTime = formatDate(acceptTime)

            this.form.goods = this.goodsSelect
            this.form.price = this.totalPrice
            let supply = this.form.supplyId.split("|")
            this.form.supplyId = supply[0]
            this.form.supplyName = supply[1]
            //处理goodsSelect中的totalprice
            for (let i = 0; i < this.form.goods.length; i++) {
              const item = this.form.goods[i]
              item.totalPrice = (item.price * item.goodsNum).toFixed(2)
            }
            addOrderlist(this.form).then(response => {
              this.$alert("新增成功", "提示", {
                confirmButtonText: "确定",
                callback: action => {
                  this.reset()
                  this.loading = false
                  //关闭页面,返回列表页面
                  this.$store.dispatch("tagsView/delView", this.$route)
                  this.$router.go(-1)
                }
                })
              })
          }
        } else {
          return false
        }
      })
    },
  }
}
</script>
